import { resolve } from "path";
import { UserConfigExport, ConfigEnv } from "vite";
import viteCompression from "vite-plugin-compression";
import requireTransform from "vite-plugin-require-transform"; // 支持require
import vue from '@vitejs/plugin-vue';

/** 当前执行node命令时文件夹的地址（工作目录） */
const root: string = process.cwd();

/** 路径查找 */
const pathResolve = (dir: string): string => {
  return resolve(__dirname, ".", dir);
};

/** 设置别名 */
const alias: Record<string, string> = {
  "@": pathResolve("src"),
  "@build": pathResolve("build")
};

export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  return {
    base: './',
    root,
    resolve: {
      alias
    },
    // 全局css
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/common/styles/mixin.scss" as *;@use "@/common/styles/variables.scss" as *;`
        }
      }
    },
    // 服务端渲染
    server: {
      // 自动开浏览器
      open: true,
      // 热更新
      hmr: {
        overlay: false
      },
      // 是否开启 https
      https: false,
      // 端口号
      port: 9567,
      host: "0.0.0.0",
      // 本地跨域代理 https://cn.vitejs.dev/config/server-options.html#server-proxy
      // proxy: {
      //   "/api": {
      //     target: "http://huangqingjian.top",
      //     changeOrigin: true,
      //     rewrite: path => path.replace(/^\/api/, "")
      //   },
      //   // "/blog-images": {
      //   //   target: "http://huangqingjian.top:9000/blog-images",
      //   //   changeOrigin: true,
      //   //   rewrite: path => path.replace(/^\/blog-images/, "")
      //   // }
      // }
    },
    plugins: [
      vue(),
      viteCompression({
        verbose: true,
        disable: false,
        deleteOriginFile: false,
        threshold: 10240,
        algorithm: "gzip",
        ext: ".gz"
      }),
      requireTransform({
        fileRegex: /.vue$|.ts$/,
      }),
    ],
    build: {
      sourcemap: false,
      chunkSizeWarningLimit: 4000,
      rollupOptions: {
        input: {
          index: pathResolve("index.html")
        },
        output: {
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]"
        }
      }
    },
    esbuild: {
      pure: mode === "production" ? ["console.log", "debugger"] : []
    },
  };
};
